<template>
  <div v-loading="viwerLoading" :class="[viwerLoading ? 'loading' : '']">
    <!-- <el-tree
      :data="sortedFilesNFolders"
      :props="treePropsSetting"
      @node-click="handleNodeClick"
    /> -->
    <div
      v-if="baseFolder.relPath !== ''"
      @click="sendAxiosPost(lastFolder)"
      class="fileFolderViewer"
    >
      <div class="inner">
        <i class="el-icon-arrow-left" />
        返回上一层
      </div>
    </div>
    <div class="fileFolderViewer" v-if="baseFolder.relPath !== ''">
      <div class="inner">
        <i class="el-icon-folder-opened" />
        当前文件夹： {{ baseFolder.relPath }}
      </div>
    </div>
    <div v-loading="viwerLoading">
      <div v-for="(item, index) in sortedFilesNFolders" :key="index">
        <file-folder-viewer @click-o="sendAxiosPost" :file-obj="item" />
      </div>
    </div>
  </div>
</template>

<script>
// @ is an alias to /src
String.prototype.replaceAll = function (FindText, RepText) {
  const regExp = new RegExp(FindText, "g");
  return this.replace(regExp, RepText);
};
export default {
  name: "file-viewer",
  props: {
    refresher: {
      required: false,
      default: "1"
    }
  },
  data() {
    return {
      viwerLoading: true,
      treePropsSetting: {
        children: "children",
        label: "name"
      },
      lastFolder: this.$obs({
        name: "",
        relPath: "",
        isDirectory: true,
        base: "",
        children: []
      }),
      baseFolder: this.$obs({
        name: "",
        relPath: "",
        isDirectory: true,
        base: "",
        children: []
      }),
      filesNFolders: []
    };
  },
  watch: {
    filesNFolders(newVal) {
      console.log("filesNFolders", newVal);
    },
    refresher() {
      this.refreshData();
    }
  },
  computed: {
    sortedFilesNFolders() {
      let sorter = (a, b) => {
        try {
          return a.name.localeCompare(b.name);
        } catch (error) {
          return false;
        }
      };
      let folders = this.filesNFolders
        .filter((ele) => {
          return ele.isDirectory;
        })
        .sort(sorter);
      let files = this.filesNFolders
        .filter((ele) => {
          return !ele.isDirectory;
        })
        .sort(sorter);
      return folders.concat(files);
    }
  },
  methods: {
    getLastFolder({ relPath }) {
      let _a = relPath.replace(/\\/g, "/");
      let _b = _a.split("/");
      _b.length > 0 && _b.pop();
      return _b.join("/");
    },
    folderSorter: function (arr) {
      let sorter = (a, b) => {
        try {
          return a.name.localeCompare(b.name);
        } catch (error) {
          return false;
        }
      };
      let folders = arr
        .filter((ele) => {
          return ele.isDirectory;
        })
        .sort(sorter);
      let files = arr
        .filter((ele) => {
          return !ele.isDirectory;
        })
        .sort(sorter);
      return folders.concat(files);
    },
    sendAxiosPost(obj) {
      if (obj.isDirectory) {
        this.viwerLoading = true;
        this.axios
          .post("/getFolder", obj)
          .then(({ data }) => {
            console.log(data); //返回的数据在这里
            this.baseFolder = this.$obs(JSON.parse(JSON.stringify(obj)));
            data.folderData && (this.filesNFolders = data.folderData);
            this.lastFolder = this.$obs(JSON.parse(JSON.stringify(obj)));
            this.$set(
              this.lastFolder,
              "relPath",
              this.getLastFolder(this.lastFolder)
            );
            this.$set(this.lastFolder, "isDirectory", true);
            this.viwerLoading = false;
          })
          .catch((error) => {
            this.viwerLoading = false;
            console.log(error); //捕获错误
          });
      } else {
        obj.relPath = obj.relPath.replace(/\\/g, "/");
        window.open("/files/" + obj.relPath);
      }
    },
    requestFolderChildren: async function (obj) {
      if (obj.isDirectory) {
        let { data } = await this.axios.post("/getFolder", obj);
        return this.folderSorter(data.folderData);
      } else {
        obj.relPath = obj.relPath.replace(/\\/g, "/");
        window.open("/files/" + obj.relPath);
      }
    },
    requestFolderChildrenTwice: async function (obj) {
      let arr = [];
      if (obj.isDirectory) {
        let { data } = await this.axios.post("/getFolder", obj);
        data.folderData.forEach(async (element) => {
          if (element.isDirectory) {
            element.children = await this.requestFolderChildren(obj);
          }
          arr.push(element);
        });
        return this.folderSorter(arr);
      } else {
        obj.relPath = obj.relPath.replace(/\\/g, "/");
        window.open("/files/" + obj.relPath);
      }
    },
    handleNodeClick: async function (obj) {
      if (!obj.isDirectory) {
        obj.relPath = obj.relPath.replace(/\\/g, "/");
        window.open("/files/" + obj.relPath);
      } else {
        // this.viwerLoading = true;
        // this.$set(obj, "children", await this.requestFolderChildrenTwice(obj));
        // this.viwerLoading = false;
      }
    },
    logger() {
      console.log(...arguments);
    },
    refreshData() {
      this.sendAxiosPost(this.baseFolder);
    }
  },
  mounted() {
    this.refreshData();
  }
};
</script>
<style lang="scss" scoped>
.loading {
  height: 500px;
  transition: all 500ms;
}
</style>
